package com.dahua.messageconsumer;

import com.alibaba.fastjson.JSON;
import com.dahua.common.config.Latest56AndEqf2Web;
import com.dahua.common.dto.Control56SmallDTO;
import com.dahua.common.dto.EquipmentFaultSmallDTO;
import com.dahua.messageconsumer.service.MyWebSocketClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.util.StringUtils;

import javax.websocket.ClientEndpointConfig;
import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.net.URI;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Executors;

@Configuration
@EnableScheduling
@Slf4j
public class SendData2Web implements SchedulingConfigurer {
    @Value("${data.web56}")
    private Integer web56;

    @Value("${web.sendEqf2Web}")
    private Integer sendEqf2Web;

    @Value("${web.control56ws}")
    private String control56ws;

    @Value("${web.equipmentfaultws}")
    private String equipmentfaultws;

    @Value("${web.rms1601ws}")
    private String rms1601ws;
    
    @Value("${web.slowrunorstopws}")
    private String slowrunorstopws;

    Session sessionsControl56;
    Session sessionEquipmentFault;
    Session sessionsRms1601;
    Session sessionsSlowRunOrStop;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(3));
    }

    @Scheduled(initialDelay = 1000, fixedDelay = 300)
    public void sendControl56() {
        sendControl56ToWeb(control56ws);
    }
    public void sendControl56ToWeb(String websocket) {
        if (web56 != 1 || StringUtils.isEmpty(websocket)) {
            return;
        }

        if (sessionsControl56 == null) {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            try {
                ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
                // 创建会话
                sessionsControl56 = container.connectToServer(MyWebSocketClient.class, clientEndpointConfig, new URI(websocket));
                log.info("websocket 连接OK --> " + websocket);
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    ;
                }
                return;
            }
        }
        if (!sessionsControl56.isOpen()) {
            try {
                sessionsControl56.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            sessionsControl56 = null;
            return;
        }
        Integer sentTimes;
        for (Integer eqid : Latest56AndEqf2Web.latestControl56sSend.keySet()) {
            sentTimes = Latest56AndEqf2Web.latestControl56sSend.get(eqid);

            if (sentTimes < 1) { // 正常情况下20秒一笔。足够时间发出去。不需要考虑同步
                Control56SmallDTO control56SmallDTO = Latest56AndEqf2Web.latestControl56s.get(eqid);
                if (control56SmallDTO != null) {
                    try {
                        sessionsControl56.getBasicRemote().sendText(JSON.toJSONString(control56SmallDTO));
                        Latest56AndEqf2Web.resetControl56(eqid);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        try {
                            sessionsControl56.close();
                        } catch (Exception e2) {
                            e2.printStackTrace();
                            return;
                        }
                        sessionsControl56 = null;
                    }
                }
            }
        }
    }

    @Scheduled(initialDelay = 1500, fixedDelay = 300)
    public void sendEquipmentFault() {
        sendEquipmentFaultToWeb(equipmentfaultws);
    }
    public void sendEquipmentFaultToWeb(String websocket) {
        if (web56 != 1 || sendEqf2Web != 1 || StringUtils.isEmpty(websocket)) {
            return;
        }

        if (sessionEquipmentFault == null) {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            try {
                ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
                // 创建会话
                sessionEquipmentFault = container.connectToServer(MyWebSocketClient.class, clientEndpointConfig, new URI(websocket));
                log.info("websocket 连接OK --> " + websocket);
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    ;
                }
                return;
            }
        }
        if (!sessionEquipmentFault.isOpen()) {
            try {
                sessionEquipmentFault.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            sessionEquipmentFault = null;
            return;
        }
        Integer sentTimes;
        for (Integer eqid : Latest56AndEqf2Web.latestEquipmentFaultsSend.keySet()) {
            sentTimes = Latest56AndEqf2Web.latestEquipmentFaultsSend.get(eqid);

            if (sentTimes < 1) { // 暂时不需要考虑同步
                List<EquipmentFaultSmallDTO> faults = Latest56AndEqf2Web.latestEquipmentFaults.get(eqid);
                if (faults != null && !faults.isEmpty()) {
                    try {
                        sessionEquipmentFault.getBasicRemote().sendText(JSON.toJSONString(faults));
                        Latest56AndEqf2Web.resetEquipmentFault(eqid);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        try {
                            sessionEquipmentFault.close();
                        } catch (Exception e2) {
                            e2.printStackTrace();
                            return;
                        }
                        sessionEquipmentFault = null;
                    }
                }
            }
        }
    }

    @Scheduled(initialDelay = 1000, fixedDelay = 300)
    public void send1601() {
        send1601ToWeb(rms1601ws);
    }
    public void send1601ToWeb(String websocket) {
        if (web56 != 1 || StringUtils.isEmpty(websocket)) {
            return;
        }

        if (sessionsRms1601 == null) {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            try {
                ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
                // 创建会话
                sessionsRms1601 = container.connectToServer(MyWebSocketClient.class, clientEndpointConfig, new URI(websocket));
                log.info("websocket 连接OK --> " + websocket);
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    ;
                }
                return;
            }
        }
        if (!sessionsRms1601.isOpen()) {
            try {
                sessionsRms1601.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            sessionsRms1601 = null;
            return;
        }
        Integer sentTimes;
        for (Integer eqid : Latest56AndEqf2Web.latest1601.keySet()) {
            sentTimes = Latest56AndEqf2Web.latest1601Send.get(eqid);

            if (sentTimes < 1) { // 正常情况下20秒一笔。足够时间发出去。不需要考虑同步
                Control56SmallDTO control56SmallDTO = Latest56AndEqf2Web.latest1601.get(eqid);
                if (control56SmallDTO != null) {
                    try {
                        sessionsRms1601.getBasicRemote().sendText(JSON.toJSONString(control56SmallDTO));
                        Latest56AndEqf2Web.reset1601(eqid);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        try {
                            sessionsRms1601.close();
                        } catch (Exception e2) {
                            e2.printStackTrace();
                            return;
                        }
                        sessionsRms1601 = null;
                    }
                }
            }
        }
    }

    @Scheduled(initialDelay = 1000, fixedDelay = 300)
    public void sendSlowRunOrStop() {
        sendSlowRunOrStopToWeb(slowrunorstopws);
    }
    public void sendSlowRunOrStopToWeb(String websocket) {
        if (web56 != 1 || StringUtils.isEmpty(websocket)) {
            return;
        }

        if (sessionsSlowRunOrStop == null) {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            try {
                ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
                // 创建会话
                sessionsSlowRunOrStop = container.connectToServer(MyWebSocketClient.class, clientEndpointConfig, new URI(websocket));
                log.info("websocket 连接OK --> " + websocket);
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    ;
                }
                return;
            }
        }
        if (!sessionsSlowRunOrStop.isOpen()) {
            try {
                sessionsSlowRunOrStop.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            sessionsSlowRunOrStop = null;
            return;
        }
        Integer sentTimes;
        for (Integer eqid : Latest56AndEqf2Web.latestSlowRunOrStop.keySet()) {
            sentTimes = Latest56AndEqf2Web.latestSlowRunOrStopSend.get(eqid);

            if (sentTimes < 1) { // 正常情况下20秒一笔。足够时间发出去。不需要考虑同步
                Integer equipmentStatus = Latest56AndEqf2Web.latestSlowRunOrStop.get(eqid);
                if (equipmentStatus != null) {
                    try {
                        sessionsSlowRunOrStop.getBasicRemote().sendText(String.format("%d %d", eqid, equipmentStatus));
                        Latest56AndEqf2Web.resetSlowRunOrStop(eqid);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        try {
                            sessionsSlowRunOrStop.close();
                        } catch (Exception e2) {
                            e2.printStackTrace();
                            return;
                        }
                        sessionsSlowRunOrStop = null;
                    }
                }
            }
        }
    }

    
    @Scheduled(initialDelay = 60000, fixedDelay = 60000)
    public void cleanCount() {
        if (LocalDateTime.now().isAfter(Latest56AndEqf2Web.checkDate)) {
            Latest56AndEqf2Web.checkDate = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);
            Latest56AndEqf2Web.cleanCount();
        }
    }
}
